package com.focusai.efairy.network.utils;

import com.focusai.efairy.network.ProgressRequestBody;
import com.focusai.efairy.network.request.base.DeletePureJSONRequest;
import com.focusai.efairy.network.request.base.MultipartRequest;
import com.focusai.efairy.network.request.base.PureJSONRequest;
import com.focusai.efairy.network.request.base.PutPureJSONRequest;
import com.focusai.efairy.network.request.base.Request;
import com.focusai.efairy.utils.log.Log;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by heqingbao on 2016/11/30.
 */
public final class OkHttpUtil {

    private static final AtomicLong mIdGenerator = new AtomicLong();

    public static okhttp3.Request createRequest(Request<?> request, String userAgent) throws Exception {
        okhttp3.Request.Builder reqBuilder = new okhttp3.Request.Builder();
        reqBuilder.url(request.getUrl());
        if (userAgent != null) {
            reqBuilder.addHeader("User-Agent", userAgent);
        }

        if (request.getMethod() == Request.Method.GET) {
            // 不能使用 HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
            // 因为HttpUrl.parse()方法不能处理ws:这种schema。在Request.Builder.url(url)方法内部会把ws:转成http:

            HttpUrl.Builder urlBuilder = reqBuilder.build().url().newBuilder();

            Map<String, String> params = request.getParams();
            for (String key : params.keySet()) {
                if (key != null) {
                    urlBuilder.addQueryParameter(key, params.get(key));
                }
            }

            reqBuilder.url(urlBuilder.build());
        } else if (request.getMethod() == Request.Method.POST) {
            if (request instanceof PureJSONRequest) {
                PureJSONRequest purgeJSONRequest = (PureJSONRequest) request;

                String pureJson = purgeJSONRequest.getPureJSON();
                Log.D("POST请求参数",pureJson);
                MediaType type = MediaType.parse(purgeJSONRequest.getMediaType());
                reqBuilder.post(RequestBody.create(type, pureJson));
            } else if (request instanceof MultipartRequest) {
                MultipartRequest<?> multipartRequest = (MultipartRequest) request;

                MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
                bodyBuilder.setType(MultipartBody.FORM);

                Map<String, String> params = multipartRequest.getParams();
                for (String key : params.keySet()) {
                    String val = params.get(key);
                    if (val != null) {
                        bodyBuilder.addFormDataPart(key, val);
                    }
                }

                Map<String, List<String>> fileMap = multipartRequest.getFilePaths();
                MediaType mediaType = MediaType.parse(((MultipartRequest) request).getMediaType());
                if (fileMap != null && !fileMap.isEmpty()) {
                    for (String key : fileMap.keySet()) {
                        List<String> paths = fileMap.get(key);
                        for (String path : paths) {
                            if (path != null && !path.isEmpty()) {
                                File f = new File(path);
                                bodyBuilder.addFormDataPart(key, f.getName(), RequestBody.create(mediaType, f));
                            }
                        }
                    }
                }

                RequestBody reqBody = bodyBuilder.build();
                if (((MultipartRequest) request).getProgressListener() != null) {
                    reqBody = new ProgressRequestBody(reqBody, ((MultipartRequest) request).getProgressListener());
                }

                reqBuilder.post(reqBody);
            } else {
                FormBody.Builder formBuilder = new FormBody.Builder();

                Map<String, String> params = request.getParams();
                for (String key : params.keySet()) {
                    String val = params.get(key);
                    if (val != null) {
                        formBuilder.add(key, val);
                    }
                }

                reqBuilder.post(formBuilder.build());
            }
        }else if (request.getMethod() == Request.Method.PUT) {
            if (request instanceof PutPureJSONRequest) {
                PutPureJSONRequest purgeJSONRequest = (PutPureJSONRequest) request;
                String pureJson = purgeJSONRequest.getPureJSON();
                MediaType type = MediaType.parse(purgeJSONRequest.getMediaType());
                reqBuilder.put(RequestBody.create(type, pureJson));
            }
        }else if (request.getMethod() == Request.Method.DELETE) {
            if (request instanceof DeletePureJSONRequest) {
                DeletePureJSONRequest purgeJSONRequest = (DeletePureJSONRequest) request;

                HttpUrl.Builder urlBuilder = reqBuilder.build().url().newBuilder();

                Map<String, String> params = request.getParams();
                for (String key : params.keySet()) {
                    if (key != null) {
                        urlBuilder.addQueryParameter(key, params.get(key));
                    }
                }
                reqBuilder.url(urlBuilder.build());
                String pureJson = purgeJSONRequest.getPureJSON();
                MediaType type = MediaType.parse(purgeJSONRequest.getMediaType());
                reqBuilder.delete();
            }
        } else {
            throw new IllegalArgumentException("暂不支持:" + request.getMethod() + "方式请求");
        }

        Map<String, String> headers = request.getHeaders();
        for (String key : headers.keySet()) {
            reqBuilder.addHeader(key, headers.get(key));
        }

        // request id
        reqBuilder.tag(mIdGenerator.getAndIncrement());

        return reqBuilder.build();
    }
}
